﻿@using CML.Intercamber.Business.Model
@{
    ViewBag.PageTitle = Resources.Intercamber.News_PageName;
}
@section PageHead
{
    <script src="/Scripts/ckeditor/ckeditor.js"></script>
    <script src="/Scripts/ckeditor/adapters/jquery.js"></script>
    <style>
        .tipWidth
        {
            max-width: 600px !important;
        }
        .cke_dialog {
            z-index: 20000 !important;
        }
    </style>
    <script type="text/javascript">
        var texts = {
            Title: '@Resources.Intercamber.Title', 
            Add: '@Resources.Intercamber.NewsAdmin_AddNews',
            Update: '@Resources.Intercamber.NewsAdmin_UpdateNews',
            ConfirmDelete: '@Resources.Intercamber.NewsAdmin_ConfirmDelete',
            Mandatory: '@Resources.Intercamber.Error_Mandatory',
            WritenByOn: '@Resources.Intercamber.NewsAdmin_WriterByOn',
            Establishment: '@Resources.Intercamber.Establishment',
            Language: '@Resources.Intercamber.Language', 
            Visible: '@Resources.Intercamber.Visible', 
            NotVisible: '@Resources.Intercamber.NotVisible'
        };

        var listLanguages = @Html.Raw(Json.Encode(ViewBag.AllLanguages));
        var listEstablishments = @Html.Raw(Json.Encode(ViewBag.AllEstablishments));
        var establishmentRestriction = @(ViewBag.EstablishmentRestriction ?? "null");
        
        var newsManager = new function() {

            var ttAdd = null;
            this.isCreatingNew = false;
            var editedId = null;
            this.openPopupAdd = function(isNew) {
                newsManager.isCreatingNew = isNew;
                if (ttAdd == null) {
                    ttAdd = $('<div />');
                    ttAdd.qtip({
                        show: {
                            effect: false,
                        },
                        content: $('#ttAdd'),
                        position: { my: 'center', at: 'center', target: $(window), viewport: $(window), adjust: { method: "shift", x: 0, y: 0 }, effect: false },
                        events: {
                            show: function() {
                                $(this).draggable();
                                $(this).qtip('option', { 'content.title': newsManager.isCreatingNew ? texts.Add : texts.Update, 'content.title.button': 'true' });
                            },
                            hide: function() {
                                $(this).qtip('option', { 'position.my': 'top left', 'position.target': [$(this).offset().left, $(this).offset().top] });
                            }
                        },
                        hide: false,
                        style: { classes: "qtip-bootstrap qtip-rounded tipWidth", tip: false }
                    });


                    var editorConfig = {
                        toolbar: [
                            { name: 'basicstyles', groups: ['basicstyles', 'cleanup'], items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat'] },
                            { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align'], items: ['BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight'] },
                            { name: 'links', items: ['Link', 'Unlink', 'Image', 'Smiley'] },
                            { name: 'styles', items: ['Styles', 'FontSize'] },
                            { name: 'colors', items: ['TextColor', 'BGColor'] }
                        ],
                        removePlugins: 'elementspath',
                        resize_enabled: false,
                        language: "@ViewBag.UiLanguage",
                        htmlEncodeOutput: true,
                        enterMode: CKEDITOR.ENTER_BR,
                        height: '200px',
                        baseFloatZIndex: 9000, 
                        filebrowserImageUploadUrl: 'UploadNewsImage'
                    };
                    CKEDITOR.replace('Message', editorConfig);
                    //$("#Message").val('');
                }
                ttAdd.qtip('option', 'content.title', isNew ? texts.Add : texts.Update);
                // load form data 
                if (establishmentRestriction != null) {
                    $("#Establishment").prop("disabled", true);
                    $("#Establishment").val(establishmentRestriction);
                }
                ttAdd.qtip('show');
                if (newsManager.isCreatingNew) {
                    $("#Title").val("");
                    CKEDITOR.instances.Message.setData("");
                    $("#FlagEnabled").prop("checked", false);
                    editedId = 0;
                } else {
                    var data = $("#gridNews").getRowData(editedId);
                    $("#Title").val(data.Title);
                    CKEDITOR.instances.Message.setData(data.Message);
                    $("#Language").val(data.IdLanguage);
                    $("#Establishment").val(data.IdEstablishment);
                    $("#FlagEnabled").prop("checked", data.Enabled == "true");
                }
            };

            this.popupHide = function() {
                ttAdd.qtip('hide');
            };

            this.save = function() {

                var valTitle = $("#Title").val();
                var valMessage = CKEDITOR.instances.Message.getData();
                var valEnabled = $("#FlagEnabled").prop("checked");
                var valLanguage = $("#Language").val();
                var valEstablishment = $("#Establishment").val();

                if (valTitle == "") {
                    alert(texts.Mandatory.replace("{0}", "@Resources.Intercamber.Title"));
                    return;
                }
                if (valMessage == "") {
                    alert(texts.Mandatory.replace("{0}", "@Resources.Intercamber.Message"));
                    return;
                }
                this.popupHide();
                $("#loading").show();

                var jsonParams = JSON.stringify({
                    Title: valTitle,
                    Message: valMessage,
                    Enabled: valEnabled,
                    IdNews: editedId,
                    IdLanguage: valLanguage,
                    IdEstablishment: valEstablishment
                });

                $.ajax({
                    type: "POST",
                    url: "/Admin/AddUpdateNews",
                    contentType: "application/json; charset=utf-8",
                    data: jsonParams,
                    dataType: "json",
                    success: function(result) {
                        $("#loading").hide();
                        if (result == true) {
                            newsManager.reloadGrid();
                        } else {
                            alert("Error!");
                        }
                    },
                    error: function(result) {
                        $("#loading").hide();
                        alert("Service error!");
                        debugger;
                    }
                });
                ttAdd.qtip('hide');
            };

            this.init = function() {
                $("#gridNews").jqGrid({
                    //autowidth: true,
                    datatype: 'json',
                    width: '100%',
                    height: '100%',
                    jsonReader: { 'repeatitems': false, 'id': 'IdNews' },
                    loadonce: true,
                    url: '/Admin/NewsData',
                    viewrecords: true,
                    colModel: [
                        { name: 'IdNews', hidden: true },
                        { name: 'LblUserCreation', hidden: true },
                        { name: 'DateCreationStr', hidden: true },
                        { name: 'Enabled', hidden: true },
                        { name: 'IdEstablishment', hidden: true },
                        { name: 'IdLanguage', hidden: true },
                        { name: 'Editable', hidden: true },
                        { name: 'Enabled', hidden: true },
                        { name: 'Title', hidden: true },
                        { name: 'IdNews', fixed: true, formatter: newsManager.gridColumnEdit, label: '@Resources.Intercamber.Edit', resizable: false, sortable: false, width: 45, index: 'IdNews', align: 'center' },
                        { name: 'IdNews', fixed: true, formatter: newsManager.gridColumnDel, label: '@Resources.Intercamber.Delete', resizable: false, sortable: false, width: 45, index: 'IdNews', align: 'center' },
                        { name: 'Info', fixed: true, formatter: newsManager.gridColumnInfo, label: '@Resources.Intercamber.Informations', width: 260, index: 'DateCreationStr', align: 'left' },
                        { name: 'Message', fixed: true, formatter: newsManager.gridColumnMessage, label: '@Resources.Intercamber.Message', width: 430, index: 'Message', align: 'left' },
                    ],
                    subGrid: false,
                    loadComplete: function() {
                        $("#gridNews").jqGrid('setGridWidth', 800, true);
                    },
                }).trigger("reloadGrid", [{ page: 1 }]);


            };

            this.reloadGrid = function() {
                $("#gridNews").jqGrid().setGridParam({ datatype: 'json', page: 1 }).trigger('reloadGrid');
            };

            this.gridColumnEdit = function(cellvalue, options, rowobject) {
                if (!rowobject.Editable)
                    return "";
                return "<img id=\"add" + cellvalue + "\" title=\"\" class='imgButton' src='/Images/Edit.gif' onclick=\"newsManager.edit(" + cellvalue + ");\" />";
            };

            this.gridColumnDel = function(cellvalue, options, rowobject) {
                if (!rowobject.Editable)
                    return "";
                return "<img id=\"del" + cellvalue + "\" title=\"\" class='imgButton' src='/Images/Delete.png' onclick=\"newsManager.delete('" + cellvalue + "', " + rowobject.NumberTeachers + ", " + rowobject.NumberStudents + ")\" />";
            };

            this.gridColumnInfo = function(cellvalue, options, rowobject) {
                var lblLanguage = "";
                var lblEstablishment = "";
                for (var i = 0, maxI = listLanguages.length; i < maxI; i++)
                    if (listLanguages[i].Id == rowobject.IdLanguage) {
                        lblLanguage = listLanguages[i].Label;
                        break;
                    }
                for (var j = 0, maxJ = listEstablishments.length; j < maxJ; j++)
                    if (listEstablishments[j].Id == rowobject.IdEstablishment) {
                        lblEstablishment = listEstablishments[j].Label;
                        break;
                    }
                var txtVisible = rowobject.Enabled ? texts.Visible : texts.NotVisible;
                return texts.Title + ": " + rowobject.Title + "<br/>" + texts.WritenByOn.replace("{0}", rowobject.LblUserCreation).replace("{1}", rowobject.DateCreationStr) + "<br/>" + texts.Establishment + ": " + lblEstablishment + "<br/>" + texts.Language + ": " + lblLanguage + "<br/>" + txtVisible;
            };
            this.gridColumnMessage = function(cellvalue, options, rowobject) {
                return rowobject.Message;
            };

            this.edit = function(id) {
                editedId = id;
                newsManager.openPopupAdd(false);
            };

            this.delete = function(id, nbTeacher, nbStudents) {
                if (!confirm(texts.ConfirmDelete))
                    return;
                $.ajax({
                    type: "POST",
                    url: "/Admin/DeleteNews",
                    contentType: "application/json; charset=utf-8",
                    data: "{'idNews':\"" + id + "\"}",
                    dataType: "json",
                    success: function(result) {
                        if (result == true)
                            newsManager.reloadGrid();
                        else
                            alert("error: " + result);
                    },
                    error: function(result) {
                        debugger;
                    }
                });
            };

        };


        $(function() {
            $(".jqbutton").button();
            $(".jqspinner").spinner();
            newsManager.init();
        });

    </script>
}

@section PageLeftBar {
    @Html.Partial("~/Views/Shared/_LeftBarUserDetailPartial.cshtml")
}

@section PageContent {
    <div class="innerTitle ui-corner-all">
        @Resources.Intercamber.News_PageName
    </div>
    <br />
    <br />
    <div>
        <button id="btnAdd" class="jqbutton" onclick="newsManager.openPopupAdd(true); return false;">@Resources.Intercamber.Add</button>
        <span id="loading" style="display: none;">
            <img src="~/Images/Loading.gif" />
            @Resources.Intercamber.Loading
        </span>
    </div>
    <br />
    <table id="gridNews" style="width: 100%"></table>

    <div id="ttAdd" style="display: none; width: 580px">
        <div style="width:100%; text-align:center">
            @Resources.Intercamber.Title
            <input type="text" id="Title" class="ui-widget-content" style="width: 400px; height:18px;" />
        </div>
        <div style="margin-top:5px;">
            <textarea id="Message"></textarea>    
        </div>
        <div style="width:100%; text-align: left;">
            @Resources.Intercamber.Establishment
            <select id="Establishment">
                <option value="">@Resources.Intercamber.All</option>
                @foreach (IdLabel establishment in ViewBag.AllEstablishments)
                {
                    <option value="@establishment.Id">@establishment.Label</option>
                }
            </select>
        </div>
        <div style="width:100%; text-align: left;">
            @Resources.Intercamber.Language 
            <select id="Language">
                <option value="fr">@Resources.Intercamber.Languages_fr</option>
                <option value="en">@Resources.Intercamber.Languages_en</option>
                <option value="es">@Resources.Intercamber.Languages_es</option>
            </select>
        </div>
        <div style="width:100%; text-align: left;">
            @Resources.Intercamber.Visible 
            <input type="checkbox" id="FlagEnabled" class="ui-widget-content"/>
        </div>

        <div class="ttButtons">
            <button class="jqbutton" onclick="newsManager.save(); return false; ">@Resources.Intercamber.Ok</button>
            &nbsp;
            <button class="jqbutton" onclick="newsManager.popupHide(); return false;">@Resources.Intercamber.Cancel</button>
        </div>
    </div>

}
